<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API优化测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .test-section {
            background: white;
            margin: 20px 0;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .test-button {
            background: #409eff;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        .test-button:hover {
            background: #337ecc;
        }
        .test-button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin: 10px 0;
            padding: 10px;
            background: #f0f9ff;
            border-left: 4px solid #409eff;
            border-radius: 4px;
        }
        .error {
            background: #fef0f0;
            border-left-color: #f56c6c;
        }
        .success {
            background: #f0f9f0;
            border-left-color: #67c23a;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 15px 0;
        }
        .stat-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            text-align: center;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #409eff;
        }
        .stat-label {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }
        .log {
            background: #2d3748;
            color: #e2e8f0;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <h1>🚀 API请求和缓存优化测试</h1>
    
    <div class="test-section">
        <h2>📊 实时统计</h2>
        <div class="stats" id="stats">
            <div class="stat-card">
                <div class="stat-value" id="cache-hits">0</div>
                <div class="stat-label">缓存命中</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="cache-hit-rate">0%</div>
                <div class="stat-label">缓存命中率</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="total-requests">0</div>
                <div class="stat-label">总请求数</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="avg-response">0ms</div>
                <div class="stat-label">平均响应时间</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="pending-requests">0</div>
                <div class="stat-label">待处理请求</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="memory-cache">0</div>
                <div class="stat-label">内存缓存项</div>
            </div>
        </div>
        <button class="test-button" onclick="updateStats()">刷新统计</button>
        <button class="test-button" onclick="clearStats()">清空统计</button>
    </div>

    <div class="test-section">
        <h2>🧪 缓存测试</h2>
        <p>测试缓存的命中和失效机制</p>
        <button class="test-button" onclick="testCache()">测试缓存效果</button>
        <button class="test-button" onclick="testCacheExpiry()">测试缓存过期</button>
        <button class="test-button" onclick="clearCache()">清空缓存</button>
        <div id="cache-results"></div>
    </div>

    <div class="test-section">
        <h2>🔄 请求去重测试</h2>
        <p>测试相同请求的去重效果</p>
        <button class="test-button" onclick="testDeduplication()">测试请求去重</button>
        <button class="test-button" onclick="testConcurrentRequests()">测试并发请求</button>
        <div id="dedup-results"></div>
    </div>

    <div class="test-section">
        <h2>📈 性能监控</h2>
        <p>查看详细的性能报告</p>
        <button class="test-button" onclick="showPerformanceReport()">显示性能报告</button>
        <button class="test-button" onclick="exportReport()">导出报告</button>
        <div id="performance-results"></div>
    </div>

    <div class="test-section">
        <h2>📝 实时日志</h2>
        <button class="test-button" onclick="clearLog()">清空日志</button>
        <div class="log" id="log"></div>
    </div>

    <script>
        // 日志函数
        function log(message, type = 'info') {
            const logElement = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${type.toUpperCase()}: ${message}\n`;
            logElement.textContent += logEntry;
            logElement.scrollTop = logElement.scrollHeight;
            
            // 同时输出到控制台
            console.log(logEntry.trim());
        }

        function clearLog() {
            document.getElementById('log').textContent = '';
        }

        // 统计更新
        function updateStats() {
            try {
                // 检查是否在主应用环境中
                if (typeof window.cacheManager === 'undefined') {
                    log('请在主应用页面中运行此测试', 'warning');
                    return;
                }

                const cacheStats = window.cacheManager.getStats();
                const requestStats = window.requestManager.getStats();
                
                // 模拟API统计（实际应用中从performanceMonitor获取）
                const apiStats = window.performanceMonitor ? 
                    window.performanceMonitor.getApiStats() : 
                    { totalRequests: 0, cacheHits: 0, cacheHitRate: 0, averageDuration: 0 };

                document.getElementById('cache-hits').textContent = apiStats.cacheHits || 0;
                document.getElementById('cache-hit-rate').textContent = `${(apiStats.cacheHitRate || 0).toFixed(1)}%`;
                document.getElementById('total-requests').textContent = apiStats.totalRequests || 0;
                document.getElementById('avg-response').textContent = `${(apiStats.averageDuration || 0).toFixed(0)}ms`;
                document.getElementById('pending-requests').textContent = requestStats.pendingRequests || 0;
                document.getElementById('memory-cache').textContent = cacheStats.memorySize || 0;

                log('统计信息已更新');
            } catch (error) {
                log(`更新统计失败: ${error.message}`, 'error');
            }
        }

        function clearStats() {
            if (window.performanceMonitor) {
                window.performanceMonitor.clear();
                log('性能统计已清空');
            }
            updateStats();
        }

        // 缓存测试
        function testCache() {
            log('开始缓存测试...');
            
            if (typeof window.cacheManager === 'undefined') {
                log('缓存管理器不可用', 'error');
                return;
            }

            const testKey = 'test_cache_' + Date.now();
            const testData = { message: 'Hello Cache!', timestamp: Date.now() };

            // 设置缓存
            window.cacheManager.set(testKey, testData, 10000); // 10秒缓存
            log(`设置缓存: ${testKey}`);

            // 立即读取
            const cached = window.cacheManager.get(testKey);
            if (cached && cached.message === testData.message) {
                log('✅ 缓存读取成功', 'success');
                document.getElementById('cache-results').innerHTML = 
                    '<div class="result success">缓存测试通过！数据正确存储和读取。</div>';
            } else {
                log('❌ 缓存读取失败', 'error');
                document.getElementById('cache-results').innerHTML = 
                    '<div class="result error">缓存测试失败！</div>';
            }
        }

        function testCacheExpiry() {
            log('测试缓存过期...');
            
            if (typeof window.cacheManager === 'undefined') {
                log('缓存管理器不可用', 'error');
                return;
            }

            const testKey = 'test_expiry_' + Date.now();
            const testData = { message: 'Will expire soon' };

            // 设置1秒过期的缓存
            window.cacheManager.set(testKey, testData, 1000);
            log(`设置1秒过期缓存: ${testKey}`);

            // 2秒后检查
            setTimeout(() => {
                const cached = window.cacheManager.get(testKey);
                if (cached === null) {
                    log('✅ 缓存过期测试通过', 'success');
                    document.getElementById('cache-results').innerHTML = 
                        '<div class="result success">缓存过期机制正常工作！</div>';
                } else {
                    log('❌ 缓存过期测试失败', 'error');
                    document.getElementById('cache-results').innerHTML = 
                        '<div class="result error">缓存过期机制异常！</div>';
                }
            }, 2000);
        }

        function clearCache() {
            if (window.cacheManager) {
                window.cacheManager.clear();
                log('所有缓存已清空');
                document.getElementById('cache-results').innerHTML = 
                    '<div class="result">缓存已清空</div>';
            }
        }

        // 请求去重测试
        function testDeduplication() {
            log('测试请求去重...');
            document.getElementById('dedup-results').innerHTML = 
                '<div class="result">请求去重测试需要在主应用中进行，请查看网络面板观察请求数量。</div>';
        }

        function testConcurrentRequests() {
            log('测试并发请求控制...');
            document.getElementById('dedup-results').innerHTML = 
                '<div class="result">并发请求测试需要在主应用中进行，请观察网络请求的并发数量。</div>';
        }

        // 性能报告
        function showPerformanceReport() {
            if (window.performanceMonitor) {
                window.performanceMonitor.logReport();
                log('性能报告已输出到控制台');
                document.getElementById('performance-results').innerHTML = 
                    '<div class="result success">性能报告已输出到浏览器控制台，请按F12查看。</div>';
            } else {
                log('性能监控器不可用', 'error');
                document.getElementById('performance-results').innerHTML = 
                    '<div class="result error">性能监控器不可用，请在主应用中运行。</div>';
            }
        }

        function exportReport() {
            if (window.performanceMonitor) {
                const report = window.performanceMonitor.exportReport();
                const blob = new Blob([report], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `performance-report-${new Date().toISOString().slice(0, 19)}.json`;
                a.click();
                URL.revokeObjectURL(url);
                log('性能报告已导出');
            }
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            log('测试页面已加载');
            log('请确保在主应用页面中运行此测试以获得完整功能');
            
            // 定期更新统计
            setInterval(updateStats, 5000);
            updateStats();
        });
    </script>
</body>
</html>
